import React, { useEffect, useState } from 'react'
import Taro from "@tarojs/taro";
import './app.less';

interface UserType {
  user: any,
  reloadUser: () => void
}

export const UserContext = React.createContext({} as UserType)
const App = (props) => {

  const [user, setUser] = useState({})


  const fetchData = async () => {
    const openid = Taro.getStorageSync('openid')
    if (!openid) {
      const resp = await Taro.request({
        url: `${process.env.PREFIX}/mock-user`,
        method: 'POST'
      })
      setUser(resp.data.data)
      Taro.setStorageSync('openid', resp.data.data.openid)
    } else {
      const resp = await Taro.request({
        url: `${process.env.PREFIX}/user/${openid}`,
      })
      setUser(resp.data.data)
    }
  }
  useEffect(() => {
    fetchData()
  }, [])

  const reloadUser = () => {
    fetchData()
  }


  return (
    <UserContext.Provider value={{ user, reloadUser }}>
      {props.children}
    </UserContext.Provider>
  )
}

export default App
